import os
import sys
from typing import List, Dict, Any, Optional

# Add project root directory to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

from User.BaseUser import BaseUser


class Student(BaseUser):
    """Student class, inherits from BaseUser"""
    
    def __init__(self, ID: str, Password: str, ChineseName: str, EnglishName: str, Group: Optional[str] = None, Courses: Optional[List] = None):
        """Initialize student information"""
        super().__init__(ID, Password, "Student")
        self.ChineseName = ChineseName
        self.EnglishName = EnglishName
        self.Group = Group  # Group number
        self.Courses = Courses if Courses is not None else []  # Enrolled courses
        self.SubmittedAssignments = {}  # Submitted assignments {assignment_id: submission}
    
    def view_dashboard(self) -> str:
        """View student dashboard"""
        course_info = "\n".join([f"- {course.CourseName} ({course.ID})" for course in self.Courses])
        progress = self.view_progress()
        
        return (f"=== Student Dashboard ===\n"
                f"ID: {self.ID}\n"
                f"Name: {self.ChineseName} ({self.EnglishName})\n"
                f"Group: {self.Group if self.Group else 'Unassigned'}\n"
                f"Enrolled Courses ({len(self.Courses)}):\n{course_info}\n"
                f"Overall Progress: {progress['overall_completion']:.2%}\n"
                f"Average Score: {progress['average_score'] if progress['average_score'] else 'No scores yet'}")
    
    def enroll_course(self, course) -> bool:
        """Enroll in a course"""
        from Course.Course import Course
        
        if not isinstance(course, Course):
            return False
            
        if course not in self.Courses:
            self.Courses.append(course)
            course.add_student(self)
            return True
            
        return False
    
    def drop_course(self, course) -> bool:
        """Drop a course"""
        from Course.Course import Course
        
        if not isinstance(course, Course):
            return False
            
        if course in self.Courses:
            self.Courses.remove(course)
            course.remove_student(self)
            
            # Also remove assignment submissions for this course
            for assignment_id in list(self.SubmittedAssignments.keys()):
                if any(a.ID == assignment_id for a in course.Assignments):
                    del self.SubmittedAssignments[assignment_id]
                    
            return True
            
        return False
    
    def submit_assignment(self, assignment, content: str) -> bool:
        """Submit an assignment"""
        from Assignment.Assignment import Assignment
        
        if not isinstance(assignment, Assignment):
            return False
            
        # Check if enrolled in the course
        if assignment.Course not in self.Courses:
            return False
            
        # Submit assignment
        submission = assignment.submit(self, content)
        self.SubmittedAssignments[assignment.ID] = submission
        return True
    
    def view_progress(self) -> Dict[str, Any]:
        """View learning progress"""
        total_assignments = 0
        submitted_assignments = 0
        scores = []
        
        for course in self.Courses:
            course_progress = course.get_student_progress(self)
            total_assignments += course_progress["total_assignments"]
            submitted_assignments += course_progress["submitted_assignments"]
            
            if course_progress["average_score"] is not None:
                scores.append(course_progress["average_score"])
                
        overall_completion = submitted_assignments / total_assignments if total_assignments > 0 else 0
        average_score = sum(scores) / len(scores) if scores else None
        
        return {
            "overall_completion": overall_completion,
            "total_assignments": total_assignments,
            "submitted_assignments": submitted_assignments,
            "average_score": average_score
        }
    
    def view_course_assignments(self, course) -> List[Dict[str, Any]]:
        """View course assignment status"""
        from Course.Course import Course
        
        if not isinstance(course, Course):
            return []
            
        assignments = []
        for assignment in course.Assignments:
            submission = assignment.get_submission_by_student(self)
            
            assignments.append({
                "assignment_id": assignment.ID,
                "title": assignment.Title,
                "deadline": assignment.Deadline,
                "submitted": submission is not None,
                "submitted_at": submission.submitted_at if submission else None,
                "grade": submission.grade if submission and submission.grade else None,
                "feedback": submission.feedback if submission and submission.feedback else None
            })
            
        return assignments
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for persistence"""
        base_dict = super().to_dict()
        return {
            **base_dict,
            "chinese_name": self.ChineseName,
            "english_name": self.EnglishName,
            "group": self.Group,
            "courses": [course.ID for course in self.Courses]
        }